package com.pn.taikao.controller;

import com.pn.taikao.dto.ApiResponse;
import com.pn.taikao.dto.CreateResponse;
import com.pn.taikao.dto.PageResult;
import com.pn.taikao.dto.QuestionQueryRequest;
import com.pn.taikao.entity.Course;
import com.pn.taikao.entity.Question;
import com.pn.taikao.entity.User;
import com.pn.taikao.service.CourseService;
import com.pn.taikao.service.QuestionService;
import com.pn.taikao.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/questions")
public class QuestionController {

    private final QuestionService questionService;
    private final CourseService courseService;

    public QuestionController(QuestionService questionService, CourseService courseService) {
        this.questionService = questionService;
        this.courseService = courseService;
    }

    /**
     * 创建题目（教师权限）
     */
    @PostMapping
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<CreateResponse> create(@RequestBody Question question) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        // 检查课程是否存在
        if (question.getCourseId() != null) {
            Course course = courseService.getById(question.getCourseId());
            if (course == null) {
                return ApiResponse.error("课程不存在");
            }
            
            // 教师只能为自己的课程创建题目
            User currentUser = SecurityUtils.getCurrentUser();
            if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
                if (!course.getTeacherId().equals(currentUserId)) {
                    return ApiResponse.error("无权限为该课程创建题目");
                }
            }
        }
        
        question.setCreateBy(SecurityUtils.getCurrentUsername());
        Long id = questionService.createQuestion(question);
        return ApiResponse.success(new CreateResponse(id));
    }

    /**
     * 更新题目（教师权限，只能更新自己创建的题目）
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> update(@PathVariable("id") Long id, @RequestBody Question question) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        // 检查题目是否存在
        Question existQuestion = questionService.getById(id);
        if (existQuestion == null) {
            return ApiResponse.error("题目不存在");
        }
        
        // 检查课程权限
        if (existQuestion.getCourseId() != null) {
            Course course = courseService.getById(existQuestion.getCourseId());
            if (course != null) {
                User currentUser = SecurityUtils.getCurrentUser();
                if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
                    if (!course.getTeacherId().equals(currentUserId)) {
                        return ApiResponse.error("无权限修改该题目");
                    }
                }
            }
        }
        
        question.setId(id);
        question.setUpdateBy(SecurityUtils.getCurrentUsername());
        questionService.updateQuestion(question);
        return ApiResponse.success(null);
    }

    /**
     * 删除题目（教师权限，只能删除自己创建的题目）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('TEACHER') or hasRole('ADMIN')")
    public ApiResponse<Void> delete(@PathVariable("id") Long id) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        if (currentUserId == null) {
            return ApiResponse.error("未登录");
        }
        
        // 检查题目是否存在
        Question existQuestion = questionService.getById(id);
        if (existQuestion == null) {
            return ApiResponse.error("题目不存在");
        }
        
        // 检查课程权限
        if (existQuestion.getCourseId() != null) {
            Course course = courseService.getById(existQuestion.getCourseId());
            if (course != null) {
                User currentUser = SecurityUtils.getCurrentUser();
                if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
                    if (!course.getTeacherId().equals(currentUserId)) {
                        return ApiResponse.error("无权限删除该题目");
                    }
                }
            }
        }
        
        questionService.deleteQuestion(id);
        return ApiResponse.success(null);
    }

    /**
     * 查询题目详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<Question> detail(@PathVariable("id") Long id) {
        Question question = questionService.getById(id);
        if (question == null) {
            return ApiResponse.error("题目不存在");
        }
        return ApiResponse.success(question);
    }

    /**
     * 根据课程ID获取题目列表（不分页，用于下拉选择）
     */
    @GetMapping("/course/{courseId}")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<List<Question>> getByCourse(@PathVariable("courseId") Long courseId) {
        List<Question> questions = questionService.getByCourseId(courseId);
        return ApiResponse.success(questions);
    }

    /**
     * 分页查询题目列表
     */
    @PostMapping("/query")
    @PreAuthorize("hasAnyRole('ADMIN','TEACHER','STUDENT')")
    public ApiResponse<PageResult<Question>> list(@RequestBody QuestionQueryRequest request) {
        // 处理默认值
        int page = (request.getPage() != null && request.getPage() > 0) ? request.getPage() : 1;
        int size = (request.getSize() != null && request.getSize() > 0) ? request.getSize() : 10;
        
        // 如果不是管理员，教师只能查看自己课程的题目
        Long courseId = request.getCourseId();
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser != null && !currentUser.getRoleType().equalsIgnoreCase("ADMIN")) {
            if (currentUser.getRoleType().equalsIgnoreCase("TEACHER")) {
                // 教师只能查看自己创建的课程的题目
                // 这里可以进一步限制，但为了简化，先允许教师查看所有自己课程的题目
            }
        }
        
        List<Question> data = questionService.list(
            request.getType(), 
            courseId, 
            request.getDifficulty(), 
            request.getContent(), 
            page, 
            size
        );
        long total = questionService.count(
            request.getType(), 
            courseId, 
            request.getDifficulty(), 
            request.getContent()
        );
        PageResult<Question> pageResult = new PageResult<>(data, total, page, size);
        return ApiResponse.success(pageResult);
    }
}



